/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2019/3/31 0:20
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.datasource;

import com.hyacinth.utils.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 数据源基础类
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
public abstract class BaseDataSource implements HYDateSource{

    private final Logger LOGGER = LoggerFactory.getLogger(getClass());

    private static final int DEFAULT_CONN_POLL_SIZE = 10;

    DataSource dataSource;

    {
        // 类加载是执行，数据源销毁操作
        Runtime.getRuntime().addShutdownHook(new Thread(this::destroy, "sys-destroy-thread"));
    }


    @Override
    public DataSource getDataSource() {
        return this.dataSource;
    }

    @Override
    public void setDataSource(String driver, String url, String username, String password) {
        setDataSource(driver, url, username, password, DEFAULT_CONN_POLL_SIZE);
    }

    @Override
    public void setDataSource(String driver, String url, String username, String password, int connPollSize) {
        checkDataSource(driver, url, username, password, connPollSize);
        try {
            initDataSource(driver, url, username, password, connPollSize);
        } catch (SQLException e) {
            LOGGER.error("initial druid datasource error", e);
        }
    }

    private void checkDataSource(String driver, String url, String username, String password, int connPollSize) {
        // 参数校验
        Assert.notNull(driver, "driver name is required");
        Assert.notNull(url, "url is required");
        Assert.notNull(username, "username is required");
        Assert.notNull(password, "password is required");
        Assert.state(connPollSize > 0, "conn poll size must be greater than zero");
    }

    @Override
    public void destroy() {
        closeDataSource();
    }

    @Override
    public void close() {
        closeDataSource();
    }

    protected abstract void initDataSource(String driver, String url, String username, String password, int connPollSize) throws SQLException;

    protected abstract void closeDataSource();
}
